﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace AIVision.MaoKe01.Application.Toolkit
{
    public static class XmlHelper
    {
        /// <summary>
        /// 从XML文件读取并反序列化为对象
        /// </summary>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="filePath">XML文件路径</param>
        /// <returns>反序列化后的对象</returns>
        public static T DeserializeFromXml<T>(string filePath) where T : class
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("XML文件不存在", filePath);
            }

            try
            {
                // 创建序列化器（指定目标类型）
                var serializer = new XmlSerializer(typeof(T));

                // 读取文件并反序列化
                using (var reader = new StreamReader(filePath))
                {
                    return serializer.Deserialize(reader) as T;
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("XML反序列化失败", ex);
            }
        }

        // 附加：序列化对象到XML文件的方法（可选）
        public static void SerializeToXml<T>(T obj, string filePath) where T : class
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            try
            {
                var serializer = new XmlSerializer(typeof(T));
                using (var writer = new StreamWriter(filePath))
                {
                    serializer.Serialize(writer, obj);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("XML序列化失败", ex);
            }
        }
    }
}
